package org.zero.onlinesubject.handler;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zero.onlinesubject.common.constant.RedisConstant;
import org.zero.onlinesubject.entity.User;
import org.zero.onlinesubject.utils.JwtUtil;
import org.zero.onlinesubject.utils.UserContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class TokenRefreshHandler implements HandlerInterceptor {

    private JwtUtil jwtUtil;

    private StringRedisTemplate stringRedisTemplate;

    public TokenRefreshHandler(JwtUtil jwtUtil, StringRedisTemplate stringRedisTemplate) {
        this.jwtUtil = jwtUtil;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if(!(handler instanceof HandlerMethod)){
//            //handler 可能是 RequestResourceHandler springboot 程序 访问静态资源 默认去classpath下的static目录去查询
//            return true;
//        }

        String token = request.getHeader("Auth-token");
        if(StringUtils.isNullOrEmpty(token)){
            return true;
        }
        Claims claims = jwtUtil.parseToken(token);
        if(claims==null){
            return true;
        }

        String id = claims.getId();
        String userInfo = stringRedisTemplate.opsForValue().get(RedisConstant.TOKEN_PREFIX + id);
        if(StringUtils.isNullOrEmpty(userInfo)){
            return true;
        }
        stringRedisTemplate.expire(RedisConstant.TOKEN_PREFIX + id,30, TimeUnit.MINUTES);
        User user = JSON.parseObject(userInfo, User.class);
        UserContextHolder.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.remove();
    }
}
